<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>
  <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" :label-width="100">
  <el-form-item label="区域名称" prop="areaName">
      <el-input v-model="dataForm.areaName" placeholder="区域名称"></el-input>
  </el-form-item>
  <el-form-item label="区域坐标" prop="areaCoordinates">
      <el-input v-model="dataForm.areaCoordinates" placeholder="点击地图选择坐标" readonly></el-input>
      <div ref="mapContainer" style="height: 400px; margin-top: 10px"></div>
  </el-form-item>

  </el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useOrderAreasApi, useOrderAreasSubmitApi } from '@/api/order/areas'
import AMapLoader from '@amap/amap-jsapi-loader'

declare namespace AMap {
  class Map {
    constructor(container: string | HTMLElement, options?: any)
    on(event: string, callback: Function): void
    setCenter(position: [number, number]): void
  }
  class Marker {
    constructor(options?: any)
    on(event: string, callback: Function): void
    setPosition(position: [number, number]): void
  }
  class Polygon {
    constructor(options?: any)
    setPath(path: Array<[number, number]>): void
  }
}

interface CustomWindow extends Window {
    _AMapSecurityConfig?: {
        securityJsCode: string;
    };
}
// 高德地图安全配置
(window as CustomWindow)._AMapSecurityConfig = {
    securityJsCode: '627ad5369b5180f5607a1ef6a7371495'
};

const emit = defineEmits(['refreshDataList'])
const visible = defineModel<boolean>('visible')
const dataFormRef = ref()
const mapContainer = ref<HTMLDivElement | null>(null)
const mapInstance = ref<any>(null)
const isMapLoaded = ref(false)

const dataForm = reactive({
	id: '',
	createTime: '',
	updateTime: '',
	deleted: '',
	areaName: '',
	areaCoordinates: '',
	areaId: '',
	updater: '',
	creator: ''})

// 加载地图
const loadMap = async () => {
    try {
        if (isMapLoaded.value) {
            return;
        }
        
        if (!mapContainer.value) {
            throw new Error('地图容器未找到');
        }
        
        isMapLoaded.value = true;

        // 显示加载状态
        ElMessage.info('正在加载地图...');
        console.log('开始加载高德地图API');

        // 确保容器可见
        mapContainer.value.style.display = 'block';
        mapContainer.value.style.height = '400px';

        // 验证安全配置
        const securityConfig = (window as CustomWindow)._AMapSecurityConfig;
        if (!securityConfig?.securityJsCode) {
            throw new Error(`地图安全配置缺失，当前配置: ${JSON.stringify(securityConfig)}`);
        }
        console.log('安全配置验证通过:', securityConfig);

        // 检查AMapLoader是否可用
        if (typeof AMapLoader.load !== 'function') {
            throw new Error('AMapLoader未正确导入');
        }

        const AMap = await AMapLoader.load({
            key: 'e45796d0ec933e587f632e1cc6b4fd0e',
            version: '2.0',
            plugins: ['AMap.Marker', 'AMap.Polygon']
        }).catch(e => {
            console.error('AMapLoader加载失败:', e);
            throw new Error(`地图API加载失败: ${e.message}`);
        });

        console.log('高德地图API加载成功:', AMap);

        // 南京七桥瓮公园坐标
        const nanjingCenter = [118.835915, 32.006999];
        mapInstance.value = new AMap.Map(mapContainer.value, {
            zoom: 15,
            viewMode: '2D',
            center: nanjingCenter
        });

        console.log('地图实例创建成功:', mapInstance.value);

        // 存储点击的坐标点
        const clickedPoints: [number, number][] = [];
        const markers: AMap.Marker[] = [];
        let polygon: AMap.Polygon | null = null;

        // 地图点击事件
        mapInstance.value.on('click', (e: any) => {
            if (clickedPoints.length >= 6) {
                return;
            }

            const position: [number, number] = [e.lnglat.getLng(), e.lnglat.getLat()];
            clickedPoints.push(position);

            // 创建标记点
            const marker = new AMap.Marker({
                position: position,
                map: mapInstance.value,
                draggable: true,
                title: `顶点${clickedPoints.length} - 可拖动`
            });
            markers.push(marker);

            // 标记点拖动事件
            marker.on('dragend', (e: any) => {
                const index = markers.indexOf(marker);
                if (index !== -1) {
                    clickedPoints[index] = [e.lnglat.getLng(), e.lnglat.getLat()];
                    updatePolygon();
                    updateCoordinates();
                }
            });

            // 提示还需多少个点
            const remainingPoints = 6 - clickedPoints.length;
            if (remainingPoints > 0) {
                ElMessage.info(`已选择${clickedPoints.length}个点，还需${remainingPoints}个点`);
            }

            // 当点击6个点时创建多边形
            if (clickedPoints.length === 6) {
                createPolygon();
                updateCoordinates();
                ElMessage.success('区域范围已创建，可拖动顶点调整');
            }
        });

        // 创建多边形
        const createPolygon = () => {
            if (polygon) {
                mapInstance.value.remove(polygon);
            }
            polygon = new AMap.Polygon({
                map: mapInstance.value,
                path: clickedPoints,
                strokeColor: "#3366FF",
                strokeWeight: 2,
                fillColor: "#3366FF",
                fillOpacity: 0.2
            });
        };

        // 更新多边形
        const updatePolygon = () => {
            if (polygon && clickedPoints.length === 6) {
                polygon.setPath(clickedPoints);
            }
        };

        // 更新坐标表单
        const updateCoordinates = () => {
            if (clickedPoints.length > 0) {
                dataForm.areaCoordinates = clickedPoints
                    .map(coord => `${coord[0]},${coord[1]}`)
                    .join(';');
            }
        };

        ElMessage.success('地图加载成功');
    } catch (error: any) {
        console.error('地图加载完整错误:', error);
        ElMessage.error(`地图加载失败: ${error.message}`);
        if (mapContainer.value) {
            mapContainer.value.innerHTML = `
                <div style="color:red;padding:20px;text-align:center">
                    <h3>地图加载失败</h3>
                    <p>${error.message}</p>
                    <p>请检查以下内容：</p>
                    <ul>
                        <li>网络连接是否正常</li>
                        <li>高德地图key是否正确</li>
                        <li>安全配置是否有效</li>
                    </ul>
                    <p>查看控制台获取更多错误信息</p>
                </div>
            `;
        }
    }
}

// 确保组件挂载后执行
onMounted(() => {
    // 添加延迟确保DOM完全渲染
    setTimeout(() => {
        if (!mapContainer.value) {
            console.error('地图容器仍未找到');
            return;
        }
        
        // 强制设置容器样式
        mapContainer.value.style.cssText = `
            width: 100%;
            height: 400px;
            margin-top: 10px;
            position: relative;
            z-index: 1;
        `;
        
        init();
    }, 300);
});

const init = (id?: number) => {
    if (id) {
        getAreas(id).then(() => {
            // 使用双重nextTick确保DOM更新完成
            nextTick(() => {
                nextTick(() => {
                    loadMap();
                    if (dataForm.areaCoordinates) {
                        const [lng, lat] = dataForm.areaCoordinates.split(',').map(Number);
                        mapInstance.value?.setCenter([lng, lat]);
                    }
                });
            });
        });
    } else {
        // 使用双重nextTick确保DOM更新完成
        nextTick(() => {
            nextTick(() => {
                loadMap();
            });
        });
    }
}

const getAreas = (id: number) => {
    return useOrderAreasApi(id).then(res => {
        Object.assign(dataForm, res.data);
        return res;
    });
}

const dataRules = ref({
	areaName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	areaCoordinates: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	areaId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate(async (valid: boolean) => {
		if (!valid) {
			return false
		}

		useOrderAreasSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>

<style scoped>
.map-container {
    width: 100%;
    height: 400px;
    margin-top: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}
</style>
